var defTeamRoleNum = 0;
var defTeamRoleCount = 1;
var isChange = false;

$(function () {
    if (editType != 'info') {
        regValidate(["#_orgBizAppDataForm"]);
    }
    if (editType == 'edit' && roleMapList && roleMapList.length > 0) {
        var str = '';
        for (var i=0; i<roleMapList.length; i++) {
            str += '<div class="form-group" id="_div_'+ defTeamRoleCount +'_teamRole">\n' +
                '                                                            <label class="col-sm-1 control-label">\n' +
                '                                                                <input type="checkbox" name="_teamRole" value="'+ defTeamRoleCount +'_teamRole" />\n' +
                '                                                            </label>\n' +
                '                                                            <div class="col-sm-3">\n' +
                '                                                                <select class="form-control" name="role" id="role'+ defTeamRoleCount +'">\n' +
                getTeamRoleOption(roleMapList[i].roleCode) +
                '                                                                </select>\n' +
                '                                                            </div>\n' +
                '                                                            <div class="col-sm-4">\n' +
                '                                                                <select class="form-control" name="docName" id="docName1">\n' +
                getDocOption(roleMapList[i].docCode) +
                '                                                                </select>\n' +
                '                                                            </div>\n' +
                '                                                            <label class="col-sm-1 control-label">排序：</label>\n' +
                '                                                            <div class="col-sm-3">\n' +
                '                                                                <input type="text" id="sortNum'+ defTeamRoleCount +'" name="sortNum" class="form-control" maxlength="9" digits="true" + value="'+ roleMapList[i].sortNum +'">\n' +
                '                                                            </div>\n' +
                '                                                        </div>';
            defTeamRoleCount++;
            defTeamRoleNum++;
        }
        $('#_teamRoleDiv').html(str);
    }
});

function doDelTeamRole() {
    var teamRoles =$('input[name="_teamRole"]:checked');
    if (!teamRoles || teamRoles.length == 0) {
        toastr.error('请先选择团队角色再删除');
        return;
    }
    var strHtml = '确认删除所选团队角色吗？';
    swalToastr('', strHtml, 'warning', deleteTeamRole);
}

function deleteTeamRole() {
    var teamRoles =$('input[name="_teamRole"]:checked');
    if (!teamRoles || teamRoles.length == 0) {
        toastr.error('请先选择团队角色再删除');
        return;
    }
    teamRoles.each(function(idx,element){
        var val = $(element).val();
        var id = '_div_' + val;
        $('#' + id).remove();
        defTeamRoleNum--;
    });
    isChange = true;
}

function doAddTeamRole() {
    if (defTeamRoleNum >= 10) {
        toastr.error('最多能添加10个团队角色');
        return;
    }
    var str = '<div class="form-group" id="_div_'+ defTeamRoleCount +'_teamRole">\n' +
        '                                                            <label class="col-sm-1 control-label">\n' +
        '                                                                <input type="checkbox" name="_teamRole" value="'+ defTeamRoleCount +'_teamRole" />\n' +
        '                                                            </label>\n' +
        '                                                            <div class="col-sm-3">\n' +
        '                                                                <select class="form-control" name="role" id="role'+ defTeamRoleCount +'">\n' +
        getTeamRoleOption() +
        '                                                                </select>\n' +
        '                                                            </div>\n' +
        '                                                            <div class="col-sm-4">\n' +
        '                                                                <select class="form-control" name="docName" id="docName1">\n' +
        getDocOption() +
        '                                                                </select>\n' +
        '                                                            </div>\n' +
        '                                                            <label class="col-sm-1 control-label">排序：</label>\n' +
        '                                                            <div class="col-sm-3">\n' +
        '                                                                <input type="text" id="sortNum'+ defTeamRoleCount +'" name="sortNum" class="form-control" maxlength="9" digits="true">\n' +
        '                                                            </div>\n' +
        '                                                        </div>';
    $('#_teamRoleDiv').append(str);
    defTeamRoleCount++;
    defTeamRoleNum++;
    isChange = true;
}

function getTeamRoleOption(roleCode) {
    var str = '';
    if (teamRoleMap && teamRoleMap.length != 0) {
        for (var i=0; i<teamRoleMap.length; i++) {
            if (teamRoleMap[i].code == teamLeaderCode) {
                continue;
            }
            str += '<option value="'+ teamRoleMap[i].code +'" '
            if (roleCode == teamRoleMap[i].code) {
                str += 'selected'
            }
            str += ' >'+ teamRoleMap[i].name +'</option>';
        }
    }
    return str;
}

function getDocOption(docCode) {
    var str = '<option value="">--请选择--</option>';
    if (docListMap && docListMap.length != 0) {
        for (var i=0; i<docListMap.length; i++) {
            str += '<option value="'+ docListMap[i].code +'" '
            if (docCode == docListMap[i].code) {
                str += 'selected'
            }
            str += ' >'+ docListMap[i].name +'</option>';
        }
    }
    return str;
}

function doCheckImage() {
    if(!$("#_orgBizAppDataForm").valid()) return;//校验不通过
    fileCheck("imgChoose", "logoImg", 10*1024, 64, 64,
        "您上传的图片大小超出限制范围（10k以内），无法上传，请重新上传符合要求的图片！",
        "您上传的图片尺寸不符合要求（64*64px），可能会影响APP展示效果，是否继续保存？", doOrgTeamSave);
}

function doOrgTeamSave() {
    var teamName = $('#teamName').val();
    var contactPhone = $('#contactPhone').val();
    var sortNum = $('#sortNum').val();
    var teamIntroduction = $('#teamIntroduction').val();
    var postData = {
        teamName : teamName,
        contactPhone : contactPhone,
        sortNum : sortNum ? sortNum : 999,
        teamIntroduction : teamIntroduction,
        isvPid : searchInfo.isvPid,
        orgCode : searchInfo.orgCode,
    };
    var teamLeader = $('#docName0').val();
    if (!teamLeader || teamLeader == '') {
        toastr.error('团队长不能为空');
        return;
    }
    var list1 = $('#_teamRoleDiv div div select');
    var list2 = $('#_teamRoleDiv div div input');
    var teamRoleList = [];
    var teamRoleInfo = {
        roleCode : teamLeaderCode,
        docCode : teamLeader,
        sortNum : 1
    };
    teamRoleList.push(teamRoleInfo);
    if (list1 && list1.length != 0) {
        if (!list2 || list2.length*2 != list1.length) {
            toastr.error('团队角色数据异常，请刷新页面重试');
            return;
        }
        for (var i=0; i<list2.length; i++) {
            var teamRoleInfo = {};
            teamRoleInfo.roleCode = list1[i*2].value;
            teamRoleInfo.docCode = list1[i*2+1].value;
            teamRoleInfo.sortNum = list2[i].value ? list2[i].value : 999;
            teamRoleList.push(teamRoleInfo);
        }
        for (var i=0; i<teamRoleList.length; i++) {
            for (var j=i+1; j<teamRoleList.length; j++) {
                if (teamRoleList[j].docCode == teamRoleList[i].docCode) {
                    toastr.error('相同专家在同一个团队不能有多个角色，请重新选择');
                    return;
                }
            }
        }
    }
    postData.teamRoleListStr = JSON.stringify(teamRoleList).replace(/\"/g,"'");
    var url = basePath + 'bizOrgTeam/addBizOrgTeam?t=' + new Date().getTime();
    if (editType == 'edit') {
        postData.id = oneBizAppInfo.id;
        postData.teamCode = oneBizAppInfo.teamCode;
        url = basePath + 'bizOrgTeam/editBizOrgTeam?t=' + new Date().getTime();
    }
    showLoading();
    $.ajaxFileUpload({
        type: 'post',
        url: url,
        dataType: 'json',
        secureuri : false,
        fileElementId : ["imgChoose"],
        contentType : "application/json; charset=UTF-8",
        data: postData,
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error(common_save_fail);
                return;
            }
            if (data.isSuccess) {
                toastr.success(common_save_success);
                doBack();
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
            return;
        }
    });
}

function doCheckDataChange() {
    var data = getFromData('#_orgBizAppDataForm');
    var checkData = {
        teamName : data.teamName,
        contactPhone : data.contactPhone,
        sortNum : data.sortNum,
        teamIntroduction : data.teamIntroduction,
    };
    if (editType != 'info' && (!Compare(checkData, oneBizAppInfo) || isChange)) {
        swalClosePageToastr(doBack);
        return;
    }
    doBack();
}

function doBack() {
    window.location.href = basePath + 'bizApp/teamPage?searchKey=' + searchInfo.searchKey +
        '&t=' + new Date().getTime() +
        '&isOrgExist=' + searchInfo.isOrgExist +
        '&isDocExist=' + searchInfo.isDocExist +
        '&orgPageNo=' + searchInfo.orgPageNo +
        '&orgPageSize=' + searchInfo.orgPageSize +
        '&pageNo=' + searchInfo.pageNo +
        '&pageSize=' + searchInfo.pageSize +
        '&status=' + searchInfo.status +
        '&dataStatus=' + searchInfo.dataStatus +
        '&docCode=' + searchInfo.docCode +
        '&docName=' + searchInfo.docName +
        '&timeInterval=' + searchInfo.timeInterval +
        '&orgCode=' + searchInfo.orgCode +
        '&teamName=' + searchInfo.teamName + '';
}